/**
 * 
 */
package edu.arizona.bio5.onto.decomposition;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.owlapi.modularity.ModuleType;
import edu.arizona.bio5.onto.decomposition.persistent.ADPersistenceException;
import edu.arizona.bio5.onto.decomposition.persistent.file.DiskADPersister;
import edu.arizona.bio5.onto.util.FileUtils;

/**
 *
 *
 * (c) Pavel Klinov
 *
 */
public class ADPersistingTaskRunner implements OntologyProcessingTaskRunner {

	private String m_folder = null;
	private ModuleType m_modType = null;
	private boolean m_labels = true;
	
	public ADPersistingTaskRunner(ModuleType modType) {
		
		this(modType, true);
	}
	
	public ADPersistingTaskRunner(ModuleType modType, boolean labels) {
		
		m_modType  = modType;
		m_labels = labels;
	}
	
	@Override
	public void setOntologyFile(File file) {
		m_folder = file.getParentFile().getAbsolutePath() + "/ad-" + m_modType.toString() + "/" + file.getName() + "/";
		//m_folder = m_folder.replace('.', '_');
	}
	/*
	 *
	 */
	@Override
	public void process(OWLOntology ontology, OWLOntologyManager mgr, Writer csvWriter) throws IOException {

		File folder = new File(m_folder);
		
		if (folder.exists()) {
			FileUtils.deleteRecursively(folder);
		}
		
		folder.mkdirs();
		//Decomposition
		if (ontology.getLogicalAxiomCount() > 20000) {
			
			System.out.println("Too big, skipping");
			
			return;
		}
		
		ChiaraDecompositionAlgorithm algo = new ChiaraDecompositionAlgorithm(m_modType); 
		AtomicDecomposition ad = algo.decompose( mgr, ontology );
		//Labeling
		if (m_labels) {

			AtomLabelingAlgorithm labelAlgo = new MSSLabelingAlgorithm();
			
			labelAlgo.compute(ad);
		}
		//Serialize the LAD
		DiskADPersister persister = new DiskADPersister();
		
		persister.setRootDir(folder);
		
		try {
			
			persister.persist(ad);
			
		} catch (ADPersistenceException e) {
			e.printStackTrace();
		}		
	}
}